﻿using Common;
using Common.EF.Controllers;
using Common.Model;
using Common.Models;
using Common.Utility;
using Common.Utility.AJ;
using Stylet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AWSV2.ViewModels
{
    public class RoleDetailViewModel : AnnotationValidationScreen<Role>
    {
        private string _title;
        public string Title
        {
            get => _title;
            set => SetAndNotify(ref _title, value);
        }

        private AJErrorInfoDialogParams _errorInfo;
        public AJErrorInfoDialogParams ErrorInfo
        {
            get => _errorInfo;
            set => SetAndNotify(ref _errorInfo, value);
        }

        private bool _addMode;
        public bool AddMode
        {
            get => _addMode;
            set => SetAndNotify(ref _addMode, value);
        }

        private bool _loading;
        public bool Loading
        {
            get => _loading;
            set => SetAndNotify(ref _loading, value);
        }

        private Role _form;
        public override Role Form
        {
            get => _form;
            set => SetAndNotify(ref _form, value);
        }

        public List<CommonTreeView> PermissionTrees { get; set; }

        private List<string> _selectedPermissionNames;

        public RoleDetailViewModel(Role form = null)
        {
            PermissionTrees = CreatePermissionTree();

            ErrorInfo = new AJErrorInfoDialogParams();

            AddMode = form == null;
            Title = AddMode
                ? I18NService.Translate(LangKeys.新增, I18NService.Translate(LangKeys.角色))
                : I18NService.Translate(LangKeys.编辑_0_, form.RoleName);
            _selectedPermissionNames = new List<string>();
            _form = new Role();
            if (form != null)
            {
                AJUtil.CopyPropertyValues(_form, form);
                if (string.IsNullOrWhiteSpace(_form.RolePermission))
                {
                    _form.RolePermission = string.Empty;
                }
                _selectedPermissionNames.AddRange(_form.RolePermission.Split(','));
                foreach (var tree in PermissionTrees)
                {
                    SetCheckedItems(tree);
                }
            }
        }

        public List<CommonTreeView> CreatePermissionTree()
        {
            var views = new List<CommonTreeView>();
            CommonTreeView _header = new CommonTreeView("所有权限");
            views.Add(_header);
            CommonTreeView _weighingOperation = new CommonTreeView("称重操作");
            CommonTreeView _weighFormTemplate = new CommonTreeView("修改磅单样式");
            CommonTreeView _backup = new CommonTreeView("数据备份恢复");
            CommonTreeView _weighRecord = new CommonTreeView("称重记录查询");
            CommonTreeView _weighPlanRecord = new CommonTreeView("计划下单查询");
            CommonTreeView _weighAccount = new CommonTreeView("称重报表统计");
            CommonTreeView _dataManagement = new CommonTreeView("数据管理");
            CommonTreeView _carPlant = new CommonTreeView("车牌");
            CommonTreeView _sysSetting = new CommonTreeView("系统设置");
            CommonTreeView _sysLog = new CommonTreeView("系统日志查询");
            _header.CreateTreeWithChildren(_weighingOperation, false);
            _header.CreateTreeWithChildren(_weighFormTemplate, false);
            _header.CreateTreeWithChildren(_backup, false);
            _header.CreateTreeWithChildren(_weighRecord, false);
            _header.CreateTreeWithChildren(_weighPlanRecord, false);
            _header.CreateTreeWithChildren(_weighAccount, false);
            _header.CreateTreeWithChildren(_dataManagement, false);
            _header.CreateTreeWithChildren(_carPlant, false);
            _header.CreateTreeWithChildren(_sysSetting, false);
            _header.CreateTreeWithChildren(_sysLog, false);
            CommonTreeView _weighing = new CommonTreeView("称重操作");
            CommonTreeView _freeWeigh = new CommonTreeView("免费放行");
            CommonTreeView _queryList = new CommonTreeView("查询列表");
            CommonTreeView _printList = new CommonTreeView("打印列表");
            CommonTreeView _exportList = new CommonTreeView("导出列表");
            CommonTreeView _deleteList = new CommonTreeView("删除列表");
            CommonTreeView _updateSelected = new CommonTreeView("修改选中");
            CommonTreeView _deleteSelected = new CommonTreeView("删除选中");
            CommonTreeView _printSelected = new CommonTreeView("补打选中");
            CommonTreeView _insertItem = new CommonTreeView("手工制单");

            CommonTreeView _updatePz = new CommonTreeView("修改皮重");
            CommonTreeView _updateMz = new CommonTreeView("修改毛重");
            CommonTreeView _updateJz = new CommonTreeView("修改净重");
            CommonTreeView _updateSz = new CommonTreeView("修改实重");

            _weighingOperation.CreateTreeWithChildren(_weighing, false);
            _weighingOperation.CreateTreeWithChildren(_freeWeigh, false);
            

            _updateSelected.CreateTreeWithChildren(_updatePz, false);
            _updateSelected.CreateTreeWithChildren(_updateMz, false);
            _updateSelected.CreateTreeWithChildren(_updateJz, false);
            _updateSelected.CreateTreeWithChildren(_updateSz, false);

            _weighRecord.CreateTreeWithChildren(_queryList, false);
            _weighRecord.CreateTreeWithChildren(_printList, false);
            _weighRecord.CreateTreeWithChildren(_exportList, false);
            _weighRecord.CreateTreeWithChildren(_deleteList, false);
            _weighRecord.CreateTreeWithChildren(_updateSelected, false);
            _weighRecord.CreateTreeWithChildren(_deleteSelected, false);
            _weighRecord.CreateTreeWithChildren(_printSelected, false);
            _weighRecord.CreateTreeWithChildren(_insertItem, false);
            _weighRecord.CreateTreeWithChildren(new CommonTreeView("导入称重记录"), false);
            _weighRecord.CreateTreeWithChildren(new CommonTreeView("修改需要密码授权"), false);


            _weighPlanRecord.CreateTreeWithChildren(new CommonTreeView("查询计划"), false);
            _weighPlanRecord.CreateTreeWithChildren(new CommonTreeView("打印计划"), false);
            _weighPlanRecord.CreateTreeWithChildren(new CommonTreeView("导出计划"), false);
            _weighPlanRecord.CreateTreeWithChildren(new CommonTreeView("删除计划"), false);
            _weighPlanRecord.CreateTreeWithChildren(new CommonTreeView("修改计划"), false);
            _weighPlanRecord.CreateTreeWithChildren(new CommonTreeView("添加计划"), false);

            CommonTreeView _queryReport = new CommonTreeView("查询报表");
            CommonTreeView _printReport = new CommonTreeView("打印报表");
            CommonTreeView _exportReport = new CommonTreeView("导出报表");
            _weighAccount.CreateTreeWithChildren(_queryReport, false);
            _weighAccount.CreateTreeWithChildren(_printReport, false);
            _weighAccount.CreateTreeWithChildren(_exportReport, false);

            CommonTreeView _user = new CommonTreeView("用户管理");
            _user.CreateTreeWithChildren(new CommonTreeView("删除用户"),false);

            CommonTreeView _role = new CommonTreeView("角色管理");
            CommonTreeView _customer = new CommonTreeView("客户管理");
            _customer.CreateTreeWithChildren(new CommonTreeView("删除客户"), false);

            CommonTreeView _car = new CommonTreeView("车辆管理");
            _car.CreateTreeWithChildren(new CommonTreeView("删除车辆"), false);

            CommonTreeView _goods = new CommonTreeView("物资管理");
            CommonTreeView _ic = new CommonTreeView("IC卡管理");
            CommonTreeView _sysField = new CommonTreeView("系统字段");
            _sysField.CreateTreeWithChildren(new CommonTreeView("删除系统字段"), false);

            CommonTreeView _poundRelField = new CommonTreeView("磅单关联");
            _poundRelField.CreateTreeWithChildren(new CommonTreeView("新增磅单关联"), false);
            _poundRelField.CreateTreeWithChildren(new CommonTreeView("修改磅单关联"), false);
            _poundRelField.CreateTreeWithChildren(new CommonTreeView("删除磅单关联"), false);

            _dataManagement.CreateTreeWithChildren(_user, false);
            _dataManagement.CreateTreeWithChildren(_role, false);
            _dataManagement.CreateTreeWithChildren(_customer, false);
            _dataManagement.CreateTreeWithChildren(_car, false);
           
            _dataManagement.CreateTreeWithChildren(_goods, false);
            _dataManagement.CreateTreeWithChildren(_ic, false);
            _dataManagement.CreateTreeWithChildren(_sysField, false);

            _dataManagement.CreateTreeWithChildren(_poundRelField, false);

            return views;
        }

        private bool _canCommit;
        public bool CanCommit
        {
            get
            {
                _canCommit = !Loading;
                return _canCommit;
            }
            set => SetAndNotify(ref _canCommit, value);
        }
        public async void Commit()
        {
            if (!ValidateModel())
            {
                ErrorInfo.Show(string.Join("\r\n", ValidationErrorsByProperty.SelectMany(p => p.Value).Select(p => p.ToString())));
                return;
            }
            _selectedPermissionNames.Clear();
            foreach (var tree in PermissionTrees)
            {
                GetCheckedItems(tree);
            }

            _form.RolePermission = string.Join(",", _selectedPermissionNames);

            Loading = true;
            try
            {
                using var ctrl = new RoleController();
                var result = await ctrl.Save(AJAutoMapperService.Instance()
                    .Mapper.Map<Role, Common.EF.Tables.Role>(_form));

                RequestClose(true);
            }
            catch (Exception e)
            {
                ErrorInfo.Show(e.Message);
            }
            finally
            {
                Loading = false;
            }
        }

        private void GetCheckedItems(CommonTreeView tree)
        {
            if (tree.IsChecked == null || tree.IsChecked == true)
            {
                _selectedPermissionNames.Add(tree.NodeName);
            }

            if (tree.Children != null && tree.Children.Count > 0)
            {
                foreach (CommonTreeView tv in tree.Children)
                    GetCheckedItems(tv);
            }
        }

        private void SetCheckedItems(CommonTreeView tree)
        {
            if (tree.Children.Count == 0)
            {
                if (_selectedPermissionNames.Exists(s => s.Equals(tree.NodeName)))
                {
                    tree.IsChecked = true;
                }
            }

            if (tree.Children != null && tree.Children.Count > 0)
            {
                foreach (CommonTreeView tv in tree.Children)
                    SetCheckedItems(tv);
            }
        }
    }
}
